package com.pbs.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pbs.contact.Contact;
import com.pbs.net.WSF;
import com.pbs.packdata.BackupInfo;
import com.pbs.ui.dialog.Dialog;
import com.pbs.ui.dialog.Dialog.Type;
import com.pbs.utils.ContactProvider;

public class RestoreContactActivity extends Activity {
	private ArrayList<BackupInfo> items = new ArrayList<BackupInfo>();
	private ListView lv;
	private ArrayAdapter<BackupInfo> aa;
	ContactProvider contactAPI;
	private String messageEmptyList = "Don't have any backup verions";
	Handler myHandler = new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.restore_screen);
		try {

			contactAPI = new ContactProvider();
			contactAPI.setCr(getContentResolver());
			contactAPI.setCur(getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI, null, null, null,
					"display_name ASC"));
			items = WSF.getAllBackupInfo(AccountManagerScreen.getUserID());

		} catch (Exception e) {
			new AlertDialog.Builder(this).setMessage(e.getMessage()).show();
		}
		lv = (ListView) findViewById(R.id.List);
		aa = new ArrayAdapter<BackupInfo>(this, R.layout.item_backup_info,
				items) {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				View v = convertView;
				if (v == null) {
					LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					v = vi.inflate(R.layout.item_backup_info, null);
				}

				TextView tvDate = (TextView) v.findViewById(R.id.tvDate);
				tvDate.setText(items.get(position).getDate());
				TextView tvTime = (TextView) v.findViewById(R.id.tvTime);
				tvTime.setText(items.get(position).getTime());
				TextView tvNote = (TextView) v.findViewById(R.id.tvNote);

				tvNote.setText("Notes: " + items.get(position).getNotes());
				CheckBox chkSelectBackupVersion = (CheckBox) v
						.findViewById(R.id.chkSelectBackupVersion);
				chkSelectBackupVersion.setChecked(items.get(position)
						.isChecked());

				return v;
			}
		};
		if (items.size() == 0) {
			((TextView) findViewById(R.id.tvMessageEmptyList))
					.setText(messageEmptyList);
		} else {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
		}
		lv.setAdapter(aa);
	}

	int numberOfItemSelected = 0;

	public void checkItemClick(View v) {
		int index = lv.getPositionForView(v);
		items.get(index).setChecked(((CheckBox) v).isChecked());
		numberOfItemSelected += ((CheckBox) v).isChecked() ? 1 : -1;
	}

	public void deleteBackupVersion(View v) {
		if (items.isEmpty()) {
			Toast.makeText(this, "Don't have any vesions to delete",
					Toast.LENGTH_LONG);
			return;
		}
		boolean hasCheck = false;
		for (BackupInfo bki : items) {
			if (bki.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			Dialog.show(this, "Delete Confirm",
					"Are you sure you want to delete?", "Yes", "No",
					new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							try {
								for (int i = 0; i < items.size(); i++) {
									if (items.get(i).isChecked()) {
										if (WSF.deleteBackupVersion(items
												.get(i).getVersionID())) {
											items.remove(i--);
											numberOfItemSelected--;
										} else {
											Toast
													.makeText(
															RestoreContactActivity.this,
															"Error while attempting to delete on server",
															Toast.LENGTH_LONG);
										}
									}
								}
								aa.notifyDataSetChanged();
								if (items.size() == 0) {
									((TextView) findViewById(R.id.tvMessageEmptyList))
											.setText(messageEmptyList);
								}
							} catch (Exception e) {
								new AlertDialog.Builder(
										RestoreContactActivity.this)
										.setMessage(
												"Exception restore 326: "
														+ e.getMessage())
										.show();
							}
						}
					}, new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}, Type.CONFIRM);
		} else {
			Toast.makeText(this, "Please choose any backup versions",
					Toast.LENGTH_LONG);
		}
	}

	public void RestoreButtonClick(View v) {
		if (items.isEmpty()) {
			Toast.makeText(this, "Don't have any versions to revert.",
					Toast.LENGTH_LONG);
			return;
		}
		if (numberOfItemSelected == 0) {
			Toast.makeText(this, "Please choose a version to revert!",
					Toast.LENGTH_LONG);
			return;
		}
		if (numberOfItemSelected == 1) {
			new AlertDialog.Builder(this)
					.setTitle("Warning")
					.setIcon(R.drawable.warning)
					.setMessage(
							"All of your current contacts will be delete.\nAre you sure you want to revert?")
					.setPositiveButton("Yes", new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							final ProgressDialog pd = Dialog
									.showProgressDialog(
											RestoreContactActivity.this,
											"Reverting...", false);
							new Thread() {
								public void run() {
									myHandler.post(new Runnable() {
										@Override
										public void run() {
											pd.setMessage("Deleting...");
										}
									});

									contactAPI.deleteContactToEnd();
									Log.i("Delete Contact", "Done!");
									Log.i("Adding Contact", "..........");

									myHandler.post(new Runnable() {
										@Override
										public void run() {
											pd
													.setMessage("Preparing to revert...");
										}
									});
									for (int i = 0; i < items.size(); i++) {
										BackupInfo info = items.get(i);
										if (info.isChecked()) {
											try {
												// Get all of backup version
												ArrayList<Contact> contacts = WSF
														.restoreContactList(info
																.getVersionID());
												Log.i("Version ID", ""
														+ info.getVersionID());
												for (int j = 0; j < contacts
														.size(); j++) {
													final Contact contact = contacts
															.remove(j);
													contactAPI
															.writeContact(contact);
													myHandler
															.post(new Runnable() {
																@Override
																public void run() {
																	pd
																			.setMessage("Reverted: "
																					+ contact
																							.getDisplayName());
																}
															});

													j--;
												}
												pd.dismiss();
												finish();
											} catch (final Exception e) {
												e.printStackTrace();
												myHandler.post(new Runnable() {
													@Override
													public void run() {
														Dialog
																.show(
																		RestoreContactActivity.this,
																		"Error!",
																		e
																				.getMessage(),
																		null,
																		null,
																		null,
																		null,
																		Type.ERROR);
													}
												});
											}
										}
									}

								}
							}.start();
						}
					}).setNegativeButton("No", new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).show();
		} else {
			Toast.makeText(this, "You are only choose a version to revert.",
					Toast.LENGTH_LONG);
		}
	}
}